package com.smsc.headend.task.engine.handler.impl.collection.strategy;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import com.smsc.headend.module.asset.entity.Meter;
import com.smsc.headend.module.data.dto.DataItemDTO;
import com.smsc.headend.module.data.entity.RdMeterReadsLp;
import com.smsc.headend.module.task.dto.AtomicTask;
import com.smsc.headend.module.task.dto.Task;
import com.smsc.headend.module.task.dto.TaskReadData;
import com.smsc.headend.task.engine.dao.TaskDAO;
import com.smsc.headend.task.engine.po.CollectDataDetailBo;
import com.smsc.headend.task.engine.service.collection.RecollectTaskService;
import org.apache.commons.lang.StringUtils;
import org.assertj.core.util.Lists;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static com.smsc.headend.task.engine.handler.impl.collection.ReadLoadProfileBufferHandler.RECOLLECT_TASK_SEQ;

public class ManualRecollectionStrategy implements CollectionStrategy {

    @Autowired
    TaskDAO taskDAO;
    @Autowired
    RecollectTaskService recollectTaskService;

    private Integer leftPointCount;

    @Override
    public List<RdMeterReadsLp> filterCollectionData(Task task, AtomicTask atomicTask, Map<String, Object> param, List<RdMeterReadsLp> meterReadsCol) {
        String recollectTaskSeq = param.get(RECOLLECT_TASK_SEQ) == null ? null : String.valueOf(param.get(RECOLLECT_TASK_SEQ));
        if (StringUtils.isEmpty(recollectTaskSeq)) {
            return Lists.emptyList();
        }
        String targetPoint = MapUtil.get(param, "targetPoint", String.class);
        String interval = MapUtil.get(param, "interval", String.class);
        CollectDataDetailBo collectDataDetailBo = recollectTaskService.handleRecollect(meterReadsCol, recollectTaskSeq, targetPoint, 9, interval);
        leftPointCount = collectDataDetailBo.getLeftPointCount();
        return meterReadsCol.stream().filter(o -> collectDataDetailBo.getHitPointTv().contains(o.getTv())).collect(Collectors.toList());
    }

    @Override
    public int callback(Meter meter, TaskReadData readData, Task task, AtomicTask atomicTask, Map<String, Object> param, List<DataItemDTO> dataItemCosemList, List<RdMeterReadsLp> filteredRdMeterReadsLp) {
        String errorText = "Success";
        String recollectTaskSeq = param.get(RECOLLECT_TASK_SEQ).toString();
        Map<String, Object> data = MapUtil.newHashMap();
        if (leftPointCount > 0) {
            errorText = "absent " + leftPointCount + " points";
        }
        data.put("value", leftPointCount);
        data.put("errorText", errorText);
        data.put("now", DateUtil.formatDateTime(new Date()));
        taskDAO.addTaskData(task.getTaskNo(), atomicTask.getAtomicTaskNo(), recollectTaskSeq, data, Long.valueOf(1 * 60 * 60), leftPointCount == 0 ? true : false);
        return 1;
    }
}
